import ApiOrder from "@/api/order";
import useRequest from "@/hooks/useRequest";
import {
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import { isUndefined } from "lodash-es";
import { h, reactive, ref } from "vue";

export default function useRefund(callback: any) {
  // 退款接口
  const {
    isFetching,
    run: runRefund,
    onFetchResponse: onResponseRefund,
  } = useRequest(ApiOrder.orderRefund, { immediate: false });

  // 提交退款成功
  onResponseRefund(() => {
    ElMessage.success("操作成功！");
    callback?.();
  });

  /**
   *  退款事件
   * @param row 数据
   */
  const refund = async (row: any, serviceType: 1 | 2 | 3) => {
    const max = parseFloat((row.pay_price / 100).toFixed(2));

    const model = reactive<{
      amount: number | undefined;
      reason: string;
    }>({
      amount: undefined,
      reason: "",
    });

    const errorMessage = ref<string>();

    await ElMessageBox({
      title: "退款确认",
      message: () =>
        h(
          "div",
          {
            style: "width:375px",
          },
          [
            h("p", { style: "margin: 0 0 12px 0" }, `最大可退额度:￥${max}`),
            h(
              ElFormItem,
              {
                label: "退款金额",
                error: errorMessage.value,
              },
              () =>
                h(ElInputNumber, {
                  max,
                  min: 0,
                  precision: 2,

                  modelValue: model.amount,
                  "onUpdate:modelValue": (e) => (model.amount = e),
                })
            ),
            h(ElFormItem, { label: "退款原因" }, () =>
              h(ElInput, {
                type: "textarea",
                placeholder: "请输入",
                modelValue: model.reason,
                "onUpdate:modelValue": (e) => (model.reason = e),
              })
            ),
          ]
        ),

      beforeClose: (action, instance, done) => {
        if (action === "confirm" && isUndefined(model.amount)) {
          errorMessage.value = "请输入正确的推荐金额";
        } else {
          done();
        }
      },
    });

    runRefund({
      sn: row.sn,
      service_type: serviceType,
      reason: model.reason,
      refundAmount: model.amount,
    });

    return;

    let refund_reason;
    let refund_amount: number | undefined = 0;
    const { value } = await ElMessageBox.prompt("请填写退款原因", "退款确认", {
      confirmButtonText: "确认退款",
      cancelButtonText: "取消",
      inputPlaceholder: "请填写",
    });
    refund_reason = value;

    runRefund({
      sn: row.sn,
      service_type: serviceType,
      reason: refund_reason,
      refundAmount: refund_amount,
    });
  };

  return {
    isFetching,
    refund,
  };
}
